const Router = require('@koa/router');
const { Ticket } = require('../databases');
const router = new Router({
    prefix: '/ticket'
});

// 获取所有门票（支持分页）
router.get('/', async (ctx) => {
    const { page = 1, pageSize = 10, sightId, sightName, priceMin, priceMax, stockMin, stockMax, ticketType, sourceChannel, status } = ctx.query;
    const offset = (parseInt(page) - 1) * parseInt(pageSize);
    const limit = parseInt(pageSize);

    // 构造筛选条件
    const where = {};
    if (sightId) {
        where.sightId = sightId;
    }
    if (priceMin !== undefined && priceMin !== '') {
        where.price = { ...(where.price || {}), $gte: Number(priceMin) };
    }
    if (priceMax !== undefined && priceMax !== '') {
        where.price = { ...(where.price || {}), $lte: Number(priceMax), ...where.price };
    }
    if (stockMin !== undefined && stockMin !== '') {
        where.stock = { ...(where.stock || {}), $gte: Number(stockMin) };
    }
    if (stockMax !== undefined && stockMax !== '') {
        where.stock = { ...(where.stock || {}), $lte: Number(stockMax), ...where.stock };
    }
    if (ticketType) {
        where.ticketType = ticketType;
    }
    if (sourceChannel) {
        where.sourceChannel = sourceChannel;
    }
    if (status) {
        where.status = status;
    }

    // 兼容 Sequelize v5/v6 写法（Op.gte/Op.lte）
    const Sequelize = require('sequelize');
    const Op = Sequelize.Op;
    if (where.price) {
        const priceCond = {};
        if (where.price.$gte !== undefined) priceCond[Op.gte] = where.price.$gte;
        if (where.price.$lte !== undefined) priceCond[Op.lte] = where.price.$lte;
        where.price = priceCond;
    }
    if (where.stock) {
        const stockCond = {};
        if (where.stock.$gte !== undefined) stockCond[Op.gte] = where.stock.$gte;
        if (where.stock.$lte !== undefined) stockCond[Op.lte] = where.stock.$lte;
        where.stock = stockCond;
    }

    // 景区名称模糊搜索，联表查询
    let include = [];
    if (sightName && sightName.trim() !== '') {
        // 关联景区表
        const { Sight } = require('../databases');
        include.push({
            model: Sight,
            as: 'sight',
            where: {
                name: { [Op.like]: `%${sightName.trim()}%` }
            },
            required: true
        });
    }

    const { count, rows } = await Ticket.findAndCountAll({
        where,
        include,
        offset,
        limit,
        order: [['ticketId', 'DESC']]
    });

    ctx.body = {
        code: 200,
        message: '获取成功',
        data: {
            list: rows,
            total: count,
            page: parseInt(page),
            pageSize: parseInt(pageSize)
        }
    };
});
// 添加门票
router.post('/add', async (ctx) => {
    const { sightId, price, desc, stock, ticketType, sourceChannel, saleStartTime, saleEndTime, status } = ctx.request.body;
    try {
        const ticket = await Ticket.create({
            sightId,
            price,
            desc,
            stock,
            ticketType,
            sourceChannel,
            saleStartTime,
            saleEndTime,
            status
        });
        ctx.body = {
            code: 200,
            message: '添加成功',
            data: ticket
        };
    } catch (error) {
        ctx.body = {
            code: 500,
            message: '添加失败',
            error: error.message
        };
    }
});
// 删除门票
router.delete('/delete/:ticketId', async (ctx) => {
    const { ticketId } = ctx.params;
    await Ticket.destroy({
        where: {
            ticketId
        }
    });
    ctx.body = {
        code: 200,
        message: '删除成功'
    };
});
// 更新门票
router.put('/update/:ticketId', async (ctx) => {
    const { ticketId } = ctx.params;
    const { sightId, price, desc, stock, ticketType, sourceChannel, saleStartTime, saleEndTime, status } = ctx.request.body;
    try {
        const ticketcontent = await Ticket.update({
            sightId,
            price,
            desc,
            stock,
            ticketType,
            sourceChannel,
            saleStartTime,
            saleEndTime,
            status
        }, {
            where: { ticketId }
        });
        if (ticketcontent[0]) {
            ctx.body = {
                code: 200,
                message: '更新成功'
            };
        } else {
            ctx.body = {
                code: 400,
                message: '更新失败'
            };
        }
    } catch (error) {
        ctx.body = {
            code: 500,
            message: '更新失败',
            error: error.message
        };
    }
});
module.exports = router;